<template>
  <div class="page white-stage">
  <top-filter ref="topFilter" @item-selected="topFilterItemSelected" :filterOptions="filterOptions" @change-filter="changeFilterValue"></top-filter>
  <search-input v-if="isShowSearch" @search-change="searchChange"></search-input>
  <div v-infinite-scroll="getClues"
        :infinite-scroll-disabled="loading"
        infinite-scroll-distance="30">
    <div  class="pdscroll" :class="{ 'hasSearch':isShowSearch}" :on-infinite="load" :on-refresh="refresh" :noDataText="noDataText" ref="my_scroller">
      <div v-if="clues.length" class="pdt scroll-container grey" :style="'padding-top:' + this.scrollerTop + 'px; height:' + this.scrollerHeight + 'px'">
        <div class="follows-list">
          <follow-item :custom_type="custom_type" v-for="(follow, index) in clues" :key="index" :follow="follow"></follow-item>
        </div>
      </div>
      <div class="no-data-tip" v-if="!clues.length && !loading">还没有跟进记录，赶紧去<router-link class="wrote-tip" :to="{path:'social-client', query:{activeItem:activeItem, title:'选择跟进客户', custom_type:custom_type, is_sf:1}}">新增</router-link>哦~</div>
      <div class="center-content-block" v-if="hasMoreData !== false">
        <mt-spinner type="snake"></mt-spinner>
      </div>
    </div>
  </div>
  <div class="list-counter" style="bottom:6px;">总计{{clues.length}}条记录</div>
  <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <router-link class="new-follow" :to="{path:'social-client', query:{activeItem:activeItem, title:'选择跟进客户', custom_type:custom_type, is_sf:1}}">新增</router-link>
  </div>
</template>

<script>
  // import Vue from 'vue'
  // import { Cell, Group } from 'vux'
  import Group from 'vux/src/components/group'
  import Cell from 'vux/src/components/cell'

  import topFilter from '../components/top-filter'
  import dropdownOption from '../components/dropdown-option'
  import followItem from '../components/follow-item'
  import crmCover from '../components/crm-cover'
  // import Scroller from 'vue-scroller'
  import SearchInput from '../components/SearchInput'

  // 按需引入加载mint-ui更多插件
  import 'mint-ui/lib/loadmore/style.css'
  import 'mint-ui/lib/spinner/style.css'
  import 'mint-ui/lib/infinite-scroll/style.css'
  import {Loadmore, Spinner} from 'mint-ui'

  import {SHOW_COVER} from '../store/mutation-types';
  import { topFilterOptions } from '../lib/options/follow-record'

  import store from '../store';


   export default{

    data() {

      let overHeight = document.body.scrollHeight+10;

      return {
        isMore: false,
        containerHeight : 'min-height:'+overHeight+'px;',
        loading: false,
        hasMoreData: true,
        scrollerHeight: '',
        scrollerTop: '',
        page_size : 15,
        page_index: 1,
        activeItem: 'h5marketing',
        originNoDataText:'暂无数据',
        noDataText:'',
        title:'',
        keyword: '',
        custom_type:0,
        clues:[],
        clueIDs: [],
        isShowSearch: false,
      }
    },

    components:{
      topFilter,
      Cell,
      Group,
      dropdownOption,
      followItem,
      crmCover,
      // Scroller,
      SearchInput,
      [Loadmore.name]: Loadmore,
      [Spinner.name]: Spinner
    },

    mounted() {
      console.debug('this.$route.query', JSON.stringify(this.$route.query));

      let query = this.$route.query;
      this.custom_type = query.custom_type;
      this.activeItem = query.activeItem;
      console.log(topFilterOptions, 'topFilterOptions')
      this.caculateScroller()
      this.getClues();

      this.callJsApi('biz.navigation.setTitle',{title:query.title});
    },

    methods: {
      caculateScroller () {
        const winHeight = window.innerHeight
        const filterHeight = this.$refs['topFilter'].$el.offsetHeight
        this.scrollerTop = filterHeight
        this.scrollerHeight = winHeight - filterHeight
      },
      refresh (iscroll) {
        this.loadStatus = 'refresh'
        this.getClues({page_index:1});
        // Refresh current data
      },

      log () {
        console.log('ee');
      },

      load (iscroll) {
        this.getClues();
      },

      test () {
        console.log('test')
      },

      //筛选器
      changeFilterValue(filterOptions){
        var submitData = Object.assign({}, this.filterData)
        this.page_index = 1;
        filterOptions.forEach((object, index) => {
          if(object.options) {
            object.options.forEach((secObject, secIndex) => {
              if(secObject.value === object.checked) {

                if(secObject.options) {
                  secObject.options.forEach((rdObj, rdIndex) => {
                    if(secObject.checked === rdObj.value) {
                      submitData[secObject.name] = rdObj.value
                    }
                  })
                } else {
                  submitData[object.name] = object.checked
                }
              }
            })
          }
        });

        let originalFilterData = this.filterData

        if(!this.isSameObj(originalFilterData, submitData)) {
          this.filterData = submitData;
          this.emptyClues();
          this.getClues();
        }

      },

      emptyClues () {
        this.clues = []
        this.clueIDs = []
        this.page_index = 1
        this.hasMoreData = true
        this.loading = false
      },

      searchChange (value) {
        console.log('searchChange',value)
        if (typeof this.sid !== 'undefined') {
          clearTimeout(this.sid)
        }

        this.sid = setTimeout(() => {
          if(!this.originClientList) {
            this.originClientList = this.clientList
          }
          this.emptyClues()
          this.keyword = value
          this.getClues()
        }, 1000)
      },

      topFilterItemSelected(item, index) {
        console.log('topFilterItemSelected')

        if (typeof item.name !== 'undefined' && item.name === 'search') {
          this.isShowSearch  = !this.isShowSearch //搜索栏打开
        } else {
          this.isShowSearch = false//打开的是筛选栏
        }

        if(this.isShowSearch === false && this.keyword) {
          if(this.isShowSearch === false) {
            this.keyword = ''
            this.emptyClues()
            this.getClues()
          }
        }

      },

      mergeClueList(data) {
        if(!this.clueIDs) this.clueIDs = []
        let newClues = []

        data.forEach((clue, index) => {

          console.log(this.clueIDs.indexOf(clue.id), 'this.clueIDs.indexOf(clue.id)')

          if(this.clueIDs.indexOf(clue.id) === -1) {
            newClues.push(clue)
            this.clueIDs.push(clue.id)
          }
        })

        if(this.loadStatus === 'refresh') {
          this.clues = newClues.concat(this.clues)
        } else {
          this.clues = this.clues.concat(newClues)
        }


        if(!this.clues.length) {
          this.noDataText = '';
        }
      },

      isSameObj (obj1, obj2) {
        return JSON.stringify(obj1) === JSON.stringify(obj2)
      },

      getClues (data) {
        let that = this;
        this.noDataText = this.originNoDataText;

        var data = Object.assign({
          page_size : this.page_size,
          custom_type : this.custom_type,
          page_index : this.page_index,
          who: 'own',
        }, this.filterData,  data || {});

        if(this.keyword) data['keyword'] = this.keyword

        if (this.loading === true || this.hasMoreData === false) return

        this.loading = true

        console.log('getClus', JSON.stringify(data))
        store.dispatch('getClues', data).then((response) => {
          const totalPage = Math.ceil(parseInt(response.data.results.total) / parseInt(this.page_size))
          this.hasMoreData = this.page_index < totalPage
          this.total = response.data.results.total
          if(response.data.errcode === 0) {
            setTimeout(() => {
              this.mergeClueList(response.data.results.data)
              this.endLoading()
            }, 1000)
          } else {
            this.endLoading()
            console.debug('系统服务异常！请联系管理员!', JSON.stringify(response.data));
          }
          this.loading = false
        }).catch((e) => {
          this.hasMoreData = false
          this.loading = false
          this.endLoading()
        })
      },

      endLoading () {
        setTimeout(() => {
          if (this.$refs.my_scroller) {
            // this.$refs.my_scroller.finishInfinite(true);
            // this.$refs.my_scroller.finishPullToRefresh();
            this.page_index++;
            this.loading = false
          }
        }, 200)
      }

    },

    computed:{

      isShowCover () {
        return this.$store.state.app.isShowCover
      },

      filterOptions() {
        return topFilterOptions;
      }

    }

   }
</script>

<style lang="less">

  @import "../less/base.less";

  .follow-pdt{
    padding-top: 40px;
  }

  .new-follow{
    background-color: #35ADFF;
    color: white;
    position: fixed;
    z-index: 80;
    bottom: 30px;
    right: 26px;
    width: 40px;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
    padding: 2px;
    border: none;
    outline: none;
    box-shadow: 0 0 10px rgba(0,0,0,.15);
    font-weight: 700;
    display: block;
    line-height: 38px;
    text-align: center;
  }
</style>
